#include "chat.h"
#include "resources.h"
#include "network.h" // MAX_CHATLEN
#include <string.h>

static char input_line[MAX_CHATLEN+1];
static int input_pos;
static char output_lines[MAX_MESSAGES_DISPLAYED][MAX_CHATLEN+1];
static int output_timeouts[MAX_MESSAGES_DISPLAYED];
static FONT* chat_font;

void chat_init(void)
{
	input_pos = 0;
	for (int i=0; i<MAX_MESSAGES_DISPLAYED; ++i) {
		output_timeouts[i] = 0;
	}
	chat_font = fnt.sans;
}

#define K_ENTER 13
#define K_BACKSPACE 8

char* chat_input(void)
{
	if (keypressed()) {
		int k = readkey();
		char c = k & 0xff;
		if (c >= ' ' && c <= 'z' && input_pos < MAX_CHATLEN) {
			input_line[input_pos++] = c;
			input_line[input_pos] = 0;
		} else if (c == K_ENTER) {
			if (input_pos >= 0) {
				input_line[input_pos] = 0; // in case of no input at all
				input_pos = 0;
				return input_line;
			}
		} else if (c == K_BACKSPACE && input_pos > 0) {
			input_line[--input_pos] = 0;
		}
	}
	return NULL;
}

void chat_receive(const char* line)
{
#define L MAX_MESSAGES_DISPLAYED-1
	for (int i=0; i<L; ++i) {
		strcpy(output_lines[i], output_lines[i+1]);
		output_timeouts[i] = output_timeouts[i+1];
	}
	strcpy(output_lines[L], line);
	output_timeouts[L] = 500;
}

void chat_update_messages(void)
{
	for (int i=0; i<MAX_MESSAGES_DISPLAYED; ++i) {
		if (output_timeouts[i] > 0) {
			output_timeouts[i]--;
		}
	}
}

void chat_display_messages(void)
{
	int i=0;
	int line_height = text_height(chat_font) + 2;
	int y = HEIGHT - MAX_MESSAGES_DISPLAYED * line_height - line_height - 40;
	int max_y = HEIGHT - line_height - 40;
	while (output_timeouts[i] <= 0 && i < MAX_MESSAGES_DISPLAYED) {
		++i;
		y += line_height;
	}
	if (y < max_y) {
		rectfill (buffer, 9, y, WIDTH - 9, max_y, makecol32(150, 150, 150));
	}
	for(; i<MAX_MESSAGES_DISPLAYED; ++i) {
		textout_ex (buffer, chat_font, output_lines[i], 10, y, -1, -1);
		y += line_height;
	}
}

void chat_display_input(void)
{
	int line_height = text_height(chat_font);
	int y = HEIGHT - line_height - 40;
	rect(buffer, 8, y - 2, WIDTH - 8, y + line_height + 2, makecol32(100, 100, 100));
	rectfill(buffer, 9, y - 1, WIDTH - 9, y + line_height + 1, makecol32(200, 200, 200));
	if (input_pos > 0) {
		textout_ex(buffer, chat_font, input_line, 10, y, -1, -1);
	}
}

